import { useState, useCallback, useEffect } from 'react'
import { useWebSocket } from './useWebSocket'

export interface PartitionInfo {
  partition: number
  leader: number
  replicas: number[]
  isr: number[]
  messageCount?: number
  latestOffset?: number
}

export function useTopicPartitions() {
  const [partitions, setPartitions] = useState<number[]>([])
  const [partitionDetails, setPartitionDetails] = useState<PartitionInfo[]>([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState<string | null>(null)
  
  const { connected } = useWebSocket()

  const loadPartitions = useCallback(async (topicName: string) => {
    if (!topicName) {
      setPartitions([])
      setPartitionDetails([])
      return
    }

    setError(null)

    // 立即显示基础分区列表（如果有缓存的话）
    const cachedPartitions = sessionStorage.getItem(`partitions_${topicName}`)
    if (cachedPartitions) {
      try {
        const cached = JSON.parse(cachedPartitions)
        setPartitions(cached.partitions || [])
        setPartitionDetails(cached.details || [])
        // 如果缓存不超过5分钟，直接使用缓存，不重新加载
        if (Date.now() - cached.timestamp < 5 * 60 * 1000) {
          return
        }
      } catch (e) {
        console.warn('解析缓存的分区信息失败:', e)
      }
    }

    // 异步加载完整的分区信息（不阻塞UI）
    setLoading(true)

    try {
      const response = await fetch(`/api/producer/topic/${topicName}/partitions`)
      
      if (response.ok) {
        const data = await response.json()
        
        if (data.success && data.partitions) {
          const partitionNumbers = data.partitions.map((p: any) => p.partition)
          const details = data.partitions.map((p: any) => ({
            partition: p.partition,
            leader: p.leader,
            replicas: p.replicas || [],
            isr: p.isr || [],
            messageCount: p.messageCount,
            latestOffset: p.latestOffset
          }))
          
          setPartitions(partitionNumbers)
          setPartitionDetails(details)
          
          // 缓存结果
          sessionStorage.setItem(`partitions_${topicName}`, JSON.stringify({
            partitions: partitionNumbers,
            details: details,
            timestamp: Date.now()
          }))
          
          // 分区信息加载完成，不需要额外的WebSocket订阅
          // 实时更新通过其他机制处理
        } else {
          setPartitions([])
          setPartitionDetails([])
        }
      } else {
        throw new Error(`HTTP ${response.status}: ${response.statusText}`)
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '加载分区信息失败'
      setError(errorMessage)
      console.error('加载分区信息失败:', err)
      
      // 如果有缓存，继续使用缓存数据
      const cachedPartitions = sessionStorage.getItem(`partitions_${topicName}`)
      if (cachedPartitions) {
        const cached = JSON.parse(cachedPartitions)
        setPartitions(cached.partitions || [])
        setPartitionDetails(cached.details || [])
      } else {
        setPartitions([])
        setPartitionDetails([])
      }
    } finally {
      setLoading(false)
    }
  }, [connected])

  const updatePartitionInfo = useCallback((topicName: string, updatedPartitions: PartitionInfo[]) => {
    setPartitionDetails(updatedPartitions)
    
    // 更新缓存
    const partitionNumbers = updatedPartitions.map(p => p.partition)
    sessionStorage.setItem(`partitions_${topicName}`, JSON.stringify({
      partitions: partitionNumbers,
      details: updatedPartitions,
      timestamp: Date.now()
    }))
  }, [])

  const clearPartitions = useCallback(() => {
    setPartitions([])
    setPartitionDetails([])
    setError(null)
    setLoading(false)
  }, [])

  // 监听WebSocket消息，处理分区信息的实时更新
  useEffect(() => {
    if (!connected) return

    const handleWebSocketMessage = (event: MessageEvent) => {
      try {
        const message = JSON.parse(event.data)

        if (message.type === 'partition_update' && message.topic && message.partitions) {
          console.log('收到分区信息更新:', message)
          updatePartitionInfo(message.topic, message.partitions)
        }
      } catch (error) {
        console.error('处理WebSocket分区更新消息失败:', error)
      }
    }

    // 添加WebSocket消息监听器
    if (window.ws && window.ws.readyState === WebSocket.OPEN) {
      window.ws.addEventListener('message', handleWebSocketMessage)
    }

    return () => {
      // 清理监听器
      if (window.ws) {
        window.ws.removeEventListener('message', handleWebSocketMessage)
      }
    }
  }, [connected, updatePartitionInfo])

  return {
    partitions,
    partitionDetails,
    loading,
    error,
    loadPartitions,
    updatePartitionInfo,
    clearPartitions
  }
}
